<template>
  <div class="content-login">
    <div class="content">
      <div class="content-input">
        <div class="title">平台运营系统</div>
        <div class="content-button">
          <lay-input v-model="formData.UserName" placeholder="用户名" allow-clear />
        </div>
        <div class="content-button">
          <lay-input
            v-model="formData.PassWord"
            type="password"
            placeholder="密码"
            password
            allow-clear
          />
        </div>
        <div class="content-button">
          <lay-button class="content-submit" type="primary" @click="signIn">
            登录
          </lay-button>
        </div>
      </div>
    </div>
  </div>
</template>
<script setup>
import { ref } from "vue";
import { useRouter } from "vue-router";
import { cache } from "@/utils/cache";
import { msgSuccess, msgError } from "@/utils/message";
import { getRoutMenu } from "@/router/menuRoute";
import { getTargetPath } from "@/utils/redirect";
import { login } from "@/api/user/login";

// 读取环境配置
const AppConfig = window.AppConfig;

const router = useRouter();
const formData = ref({
  UserName: "",
  PassWord: "",
});

const signIn = () => {
  let username = formData.value.UserName;
  let password = formData.value.PassWord;
  if (!username) {
    msgError("用户名不能为空");
    return;
  }
  if (!password) {
    msgError("密码不能为空");
    return;
  }
  login({
    username: username,
    password: password,
  }).then((res) => {
    if (res.status != 200) {
      msgError(res.message);
      return false;
    }
    cache(AppConfig.BASE_API_TOKEN_NAME + "_user", formData.value);
    cache(AppConfig.BASE_API_TOKEN_NAME, res.data.token);

    msgSuccess("登录成功");
    // 获取菜单
    getRoutMenu().then(() => {
      // 重定向到主页路由
      router.push(getTargetPath());
    });
  });
};
</script>
<style scoped>
.content-login {
  background: #f6f6f6;
  height: 100vh;
}

.content {
  width: 400px;
  height: 350px;
  box-sizing: border-box;
  padding: 0 50px;
  border-radius: 5px;
  box-shadow: 0px 2px 12px 0px rgba(105, 105, 105, 0.07);
  background: rgba(255, 255, 255, 0.5);
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  overflow: hidden;
  transition: 1.5s;
}

.content-input {
  width: 300px;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

.content-button {
  margin-top: 25px;
}

.content-submit {
  width: 100%;
}

.title {
  text-align: center;
  font-size: 18px;
  margin-bottom: 30px;
  font-weight: bold;
  color: #606266;
}
</style>
